import React, { Component } from 'react'
import { Area } from 'react-vant'
import { areaList } from '@vant/area-data'
import axios from 'axios'
export default class AddEditAddress extends Component {
  state = {
    name: '',
    phone: '',
    region: '',
    address: '',
  }
  //判断路由是编辑还是新增
  componentDidMount() {
    // console.log(this.props.location.pathname)
    if (this.props.location.pathname == '/edit') {
      //编辑路由
      const {
        id,
        item: { name, phone, region, address },
      } = this.props.location.state
      this.setState({
        name,
        phone,
        region,
        address,
      })
    }
  }
  getRegion = (v, options) => {
    console.log(v, options, 'options')
    let region = ''
    options.forEach((item) => {
      region += item.text
    })
    this.setState({ region })
  }
  //提交数据到接口
  onSubmit = () => {
    const { name, phone, region, address } = this.state
    if (name === '' || phone === '' || region === '' || address === '') {
      alert('请输入必填项')
      return
    }
    //判断是修改还是添加的数据
    if (this.props.location.pathname === '/edit') {
      const { id } = this.props.location.state
      console.log(id, this.props.location.state, 'state编辑')
      //编辑
      axios
        .get('/edit/city', { params: { name, phone, region, address, id } })
        .then(() => {
          //跳转页面
          // this.props.history.push('/')
          window.location.reload()
        })
    } else {
      axios
        .get('/add/city', { params: { name, phone, region, address } })
        .then(() => {
          //跳转页面
          // this.props.history.push('/')
          window.location.reload()
        })
    }
  }
  render() {
    return (
      <div>
        姓名：
        <input
          type="text"
          onChange={(e) => {
            this.setState({ name: e.target.value })
          }}
          value={this.state.name}
        />
        <br />
        手机号：
        <input
          type="text"
          onChange={(e) => {
            this.setState({ phone: e.target.value })
          }}
          value={this.state.phone}
        />
        <br />
        省市区：<div>{this.state.region}</div>
        <Area title="标题" areaList={areaList} onConfirm={this.getRegion} />
        详细地址：
        <input
          type="text"
          onChange={(e) => {
            this.setState({ address: e.target.value })
          }}
          value={this.state.address}
        />
        <br />
        <button onClick={this.onSubmit}>提交</button>
      </div>
    )
  }
}
